package com.spring.mvc.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.mvc.dao.UserDAO;
import com.spring.mvc.mail.SendMail;
import com.spring.mvc.pojo.CallResult;
import com.spring.mvc.pojo.User;
import com.spring.mvc.service.UserService;
import com.spring.mvc.util.ErrCode;
import com.spring.mvc.util.MailUtil;
import com.spring.mvc.util.ParamCheck;
import com.spring.mvc.util.Prompt;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private SendMail sendMail;

	@Transactional(readOnly=true)
	public CallResult login(User user) {
		CallResult result=new CallResult();
		if(ParamCheck.checkUserLogin(user, result)){
			result=userDAO.login(user);
		}
		return result;
	}

	@Transactional(readOnly=true)
	public CallResult check(String userName) {
		CallResult result=new CallResult();
		if(ParamCheck.checkUserName(userName, result)){
			result=userDAO.check(userName);
		}
		return result;
	}

	public CallResult addUser(User user) {
		CallResult result=new CallResult();
		//检查参数正确性
		ParamCheck.checkUserRegister(user, result);
		if(result.getErrCode()==ErrCode.SUCCESS){
			//检查用户是否存在
			result=check(user.getUserName());
			if(result.getErrCode()!=ErrCode.SUCCESS){
				result.setErrInfo(ErrCode.ERROR, Prompt.get("user.exists"));
			}else{
				result=userDAO.addUser(user);
				if(result.getErrCode()==ErrCode.SUCCESS){
					MailUtil.send(sendMail,user);
				}
			}
		}
		return result;
	}

	public CallResult list() {
		System.out.println("user list");
		CallResult result=userDAO.list();
		return result;
	}
}
